package ink.tsg.springboot.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiUserGetByMobileRequest;
import com.dingtalk.api.request.OapiUserGetRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiUserGetByMobileResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.taobao.api.ApiException;
import com.taobao.api.internal.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author geo_tsg
 * @version 1.0.0
 * @ClassName DingWorkService.java
 * @Description
 * @createTime 2021-11-09
 */
@Service
@Slf4j
public class DingWorkService {

    private String APP_KEY = "dingaixtha4kq48ovsk7";
    private String APP_SECRET = "t8pSDlysPIqDI1WSG_YuvoKrD13X2q9URpafnwCLmrT2IdLAFfz5qKddld7LIfmD";
    private Long AGENT_ID = 1355973749L;

    private String MESSAGE_URL = "http://47.119.187.14:9003";
    private String PC_MESSAGE_URL = "https://www.baidu.com";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:dd");

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    public static final String key = "dingding:token";

    /**
     * 获取AccessToken
     * @return  AccessToken
     * @throws ApiException
     */
    private String getAccessToken() throws ApiException {
        String token = (String) redisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(token)){
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
            OapiGettokenRequest request = new OapiGettokenRequest();
            //Appkey
            request.setAppkey(APP_KEY);
            //Appsecret
            request.setAppsecret(APP_SECRET);
            /*请求方式*/
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String accessToken = response.getAccessToken();
            redisTemplate.opsForValue().set(key,accessToken,2, TimeUnit.HOURS);
            return accessToken;
        }else{
            return token;
        }
    }

    /**
     * 发送OA消息
     * @param mobile 发送消息人的电话，多个英文逗号拼接
     * @throws ApiException
     */
    public void sendOA(String mobile) throws ApiException {
        log.info("发送钉钉通知");
        String accessToken = getAccessToken();
        if(StringUtils.isEmpty(mobile)){
            return;
        }
        //电话号码数组
        String[] split = mobile.split(",");
        for (String s : split) {
            DingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
            OapiUserGetByMobileRequest req = new OapiUserGetByMobileRequest();
            req.setMobile(s);
            req.setHttpMethod("GET");
            OapiUserGetByMobileResponse rsp = client2.execute(req, accessToken);
            //获取到Urid就是在公司里要发送到那个人的id
            String urid = rsp.getUserid();
            //根据用户id获取用户详情
            DingTalkClient userDetail = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
            OapiUserGetRequest userReq = new OapiUserGetRequest();
            userReq.setUserid(urid);
            userReq.setHttpMethod("GET");
            OapiUserGetResponse userRsp = userDetail.execute(userReq, accessToken);
            String userName = userRsp.getName();

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
            request.setUseridList(urid);
            request.setAgentId(AGENT_ID);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setOa(new OapiMessageCorpconversationAsyncsendV2Request.OA());
            //跳转链接
//            msg.getOa().setMessageUrl(MESSAGE_URL);
//            msg.getOa().setPcMessageUrl(PC_MESSAGE_URL);
            //设置head
            msg.getOa().setHead(new OapiMessageCorpconversationAsyncsendV2Request.Head());
            msg.getOa().getHead().setText("待办事宜测试");
            msg.getOa().getHead().setBgcolor("00409eff");
            //设置body
            msg.getOa().setBody(new OapiMessageCorpconversationAsyncsendV2Request.Body());
            msg.getOa().getBody().setTitle("温馨提示：别忙了！该喝水了！");
            msg.getOa().getBody().setContent("创建人：你猜"  + "\n创建时间：" + sdf.format(new Date()));
            //消息类型
            msg.setMsgtype("oa");
            request.setMsg(msg);
            log.info("获取发送通知消息体和获取发送通知人完成");
            OapiMessageCorpconversationAsyncsendV2Response response = client.execute(request,accessToken);
            log.info("发送消息是否成功"+response.isSuccess());
            System.out.println(response.isSuccess());
            log.info("消息任务ID"+response.getTaskId());
            System.out.println(response.getTaskId());
        }
    }

}
